<?php

class ApplePayModel extends Model{


	public function itemList(){
		return array(
						array(
			                'productIdentifier' => '00002',
			                'localizedTitle' => '4.2',
			                'localizedDescription' => 'PY币*4.2',
			                'price' => 6,
			                ),
	            		array(
			                'productIdentifier' => '00003',
			                'localizedTitle' => '8.4',
			                'localizedDescription' => 'PY币*8.4',
			                'price' => 12,
			                ),
			            array(
			                'productIdentifier' => '00001',
			                'localizedTitle' => '42.0',
			                'localizedDescription' => 'PY币*42.0',
			                'price' => 60,
			                ),
	            	);
	}

	private function getItemPrice($id){
		$arr = array(
			'00003' => '8.4',
			'00002' => '4.2',
			'00001' => '42.0',
			);
		return $arr[$id];
	}

	function recharge($apple_receipt){
		// $apple_receipt = '11111111111111111'; //苹果内购的验证收据,由客户端传过来
	    $jsonData = array('receipt-data'=>$apple_receipt);//这里本来是需要base64加密的，我这里没有加密的原因是客户端返回服务器端之前，已经作加密处理
	    $jsonData = json_encode($jsonData);
	    //$url = 'https://buy.itunes.apple.com/verifyReceipt';  正式验证地址
	    $url = 'https://sandbox.itunes.apple.com/verifyReceipt'; //测试验证地址
	    $response = $this->http_post_data($url,$jsonData);
	    log_file('apple_pay_response='.json_encode( $response), 'apple_pay');
	    if($response->{'status'} == 0){
	    	$account_obj = D('Account');
	    	$user_id = intval(session('user_id'));
	    	log_file('apple_pay_user='.$user_id, 'apple_pay_user');
	    	//增加余额
	    	$result = json_decode( json_encode( $response),true);
	    	$receipt = $result['receipt'];
	    	$is_handled = $account_obj->checkPayCodeExists($receipt["transaction_id"]);
	    	if($is_handled){
	    		return 'failure';
	    	}
	    	log_file('apple_pay_result='.json_encode($receipt), 'apple_pay');
	    	
	    	$item_price = $this->getItemPrice($receipt['product_id']);
	    	$account_obj->addAccount($user_id, 1, $item_price, '苹果内购充值', 0, 0, $receipt['transaction_id']);
				log_file('account_sql='.$account_obj->getLastSql(), 'apple_pay');
	    	// dump($result);die;
	        return 'success';
	    }else{
	        return $response->{'status'};
	    }
	}


	//curl请求苹果app_store验证地址
	private function http_post_data($url, $data_string) {
	    $curl_handle=curl_init();
	    curl_setopt($curl_handle,CURLOPT_URL, $url);
	    curl_setopt($curl_handle,CURLOPT_RETURNTRANSFER, true);
	    curl_setopt($curl_handle,CURLOPT_HEADER, 0);
	    curl_setopt($curl_handle,CURLOPT_POST, true);
	    curl_setopt($curl_handle,CURLOPT_POSTFIELDS, $data_string);
	    curl_setopt($curl_handle,CURLOPT_SSL_VERIFYHOST, 0);
	    curl_setopt($curl_handle,CURLOPT_SSL_VERIFYPEER, 0);
	    $response_json =curl_exec($curl_handle);
	    $response =json_decode($response_json);
	    curl_close($curl_handle);
	    return $response;
	}
}